

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author marduke
 * * basado en: http://zerioh.tripod.com/ressources/sockets.html
 */
import java.io.*;
import java.net.*;
import java.util.Enumeration;
import nanoxml.XMLElement;

public class Cliente {

    Socket requestSocket;
    ObjectOutputStream out;
    ObjectInputStream in;
    String message;
    String servidor = "127.0.0.1";
    String messageToServer;
    int puerto = 2004;

    Cliente() {
    }

    Cliente(String servidor, int puerto, String message) {
        this.servidor = servidor;
        this.puerto = puerto;
        this.messageToServer = message;

    }

    void run() {
        try {
            //1. creating a socket to connect to the server
            requestSocket = new Socket(servidor, puerto);
            System.out.println("Connected to server");
            //2. get Input and Output streams
            out = new ObjectOutputStream(requestSocket.getOutputStream());
            out.flush();
            in = new ObjectInputStream(requestSocket.getInputStream());
            //3: Communicating with the server
            do {
                try {
                    message = (String) in.readObject();
                  
                    sendMessage(messageToServer);

                    message = (String) in.readObject();

                    System.out.println("Esperando por el server");
                    
                    imprimirResultado(message);

                    message = "bye";
                    sendMessage(message);



                } catch (ClassNotFoundException classNot) {
                    System.err.println("data received in unknown format");
                }
            } while (!message.equals("bye"));
        } catch (UnknownHostException unknownHost) {
            System.err.println("El servidor no esta activado, o el ip no es el correcto.!");
//        } catch (ConnectException connectException) {
//            System.err.println("Estas tratando de conectarte a un puerto malo!");
//            System.exit(-2);
//        }
        } //         catch (SocketException socketEx) {
        //            System.out.println("Se perdio la conexion con el servidor, Vamos a intentar otra vez.");
        //            this.run();
        //        }
        catch (IOException ioException) {
            ioException.printStackTrace();
        } finally {
            //4: Closing connection
            try {
                in.close();
                out.close();
                requestSocket.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }

    }

    void sendMessage(String msg) {
        try {
            out.writeObject(msg);
            out.flush();
         //   System.out.println("client>" + msg);
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }

    void imprimirResultado(String messageServidor) {

        if (messageServidor.equals("Descargado")) {
            System.out.println("Se ha descargado");
        } else {

            XMLElement xml = new XMLElement();
            xml.parseString(messageServidor);

            if (xml.getName().equals("visitados")) {
                System.out.println("Los nodos alcanzables son:");
                Enumeration childs = xml.enumerateChildren();
                while (childs.hasMoreElements()) {
                    XMLElement child = (XMLElement) childs.nextElement();
                    System.out.println(child.getAttribute("hostaddress"));
                }

            } else if (xml.getName().equals("consulta")) {
                System.out.println("La consulta fue:");
                Enumeration childs = xml.enumerateChildren();
                while (childs.hasMoreElements()) {
                    XMLElement child = (XMLElement) childs.nextElement();
                    if(child.countChildren() > 0) {
                    System.out.println("DE LA MAQUINA: " + child.getAttribute("hostname"));
                    int contador = 1;
                    Enumeration consultas = child.enumerateChildren();

                        while (consultas.hasMoreElements()) {
                            System.out.println("ARCHIVO NRO " + contador++);
                            XMLElement consulta  = (XMLElement) consultas.nextElement();
                            Enumeration atributes =  consulta.enumerateAttributeNames();
                            while (atributes.hasMoreElements()) {
                                String atribute = (String) atributes.nextElement();
                                System.out.println(atribute.toLowerCase()+": " + consulta.getAttribute(atribute));

                            }

                        }
                    }
                }
            }

        }
    }
}
